#!/usr/bin/python3
import os
import subprocess
import urllib.request
import shutil
import argparse
import re
import codecs
import sys
from helper_function import *
from dep_check import loop_required
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    
    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''
################################
tree = "/var/slackmaster"
work = "/tmp/slackmaster/work"

slack_ver = 14
source = "http://ftp.slackware.com/pub/slackware/slackware64-14.0/source/"


class NoDeps(Exception):
    pass

class NotString(Exception):
    pass

class NoMoreDeps(Exception):
    pass



# def fetch_source_stock(sets, name):

#     # baseurl
#     base_url = source + sets + "/" + name + "/"
#     link = urllib.request.urlopen(base_url)

#     #file_list
#     file_list = source + "FILE_LIST"
#     file_list = urllib.request.urlopen(file_list)
#     f = file_list.readlines()
#     complete_name = sets + "/" + name
#fetch_source_stock("ap", "vim")

class Tree():
    def __init__(self):
        path_exist()
        self.tree = tree

    def sync_tree(self):
        subprocess.call("rsync --log-file=/var/slackmaster/potential_update.log -av rsync://slackbuilds.org/slackbuilds/14.0/ {0}".format(tree), shell=True)
        
    def remove_tree(self):
        try:
            shutil.rmtree(self.tree)
        except PermissionError:
            print("Please log in to Root to do this")


class SlackBuild():
    def __init__(self, script_name):
        path_exist()
        self.org = script_name
        try:
            self.script_name = match_name_with_cat(script_name)
            self.script_split = self.script_name.split("/")[1]

        except:
            pass

        self.work = work
        self.tree = tree
        
<<<<<<< HEAD
    def build(self):
##
        fetch_source(self.script_name)
##
        try:
            
            os.mkdir("{0}/{1}".format(self.work, self.script_split))
=======
    def search(self):
        try:
            file = open("{0}/SLACKBUILDS.TXT".format(tree))
            file = file.readlines()
            slist = []
            for lines in file:
                match = re.search("SLACKBUILD LOCATION: ..(\w+.*{0}.*)".format(self.org), lines)
                if match:
                    slist.append(match.group(1))

            return slist
                                 
                                 
     
>>>>>>> ba5e6b0982970f82d6b6fa443ce1404462fb5bcc
        except:
            print("Unexpected error")
    def build(self):

        self.fetch()
        move_file_from_tree(self.script_name, "{0}/{1}".format(self.work, self.script_split))
        os.chdir(self.work + "/" + self.script_split)
        subprocess.call("bash {0}/{1}/{1}.SlackBuild".format(self.work, self.script_split), shell=True)
<<<<<<< HEAD
##
        subprocess.call("upgradepkg --install-new /tmp/*{0}*.t?z".format(self.script_split), shell=True)
##
=======
        




    def get_downloads_link(self):
        f = open("{0}/{1}/{2}.info".format(self.tree, self.script_name, self.script_split))
        file = f.readlines()

        stripped_dl_list = []
        dl_list = []
        for line in file:
            if line.startswith("\tftp") or line.startswith("\thttp") or line.startswith("DOWNLOAD="):
                dl_list.append(line)

        for main_download in dl_list:
            if main_download.startswith('DOWNLOAD="'):
                self.stripped_master_link = main_dl_link(main_download)
                stripped_dl_list.insert(0, self.stripped_master_link)
                

        for alternative_download in dl_list:
            if alternative_download.startswith("\tftp") or alternative_download.startswith("\thttp"):
                self.stripped_alt_download = strip_dl_link(alternative_download)
                stripped_dl_list.append(self.stripped_alt_download)

        return(stripped_dl_list)



    def fetch(self):
        try:
            shutil.rmtree("{0}/{1}".format(self.work, self.script_split))
            os.mkdir("{0}/{1}".format(self.work, self.script_split))
        except:
            os.mkdir("{0}/{1}".format(self.work, self.script_split))
            
        
        for files_to_download in get_downloads_link(self.script_name):
            try:
                self.stripped_basename = os.path.basename(files_to_download)
                print("Downloading {0}...".format(self.stripped_basename))
                print(files_to_download)
                urllib.request.urlretrieve(files_to_download, filename="{0}/{1}/{2}".format(self.work, self.script_split, self.stripped_basename))
                print(bcolors.OKGREEN + "Downloaded sources for {0} sucessfully!".format(self.script_split) + bcolors.ENDC)
            except:
                print(bcolors.FAIL + "Fetching sources for {0} failed".format(self.script_split) + bcolors.ENDC)



def update():
    list_ver = []
    list_name = []
    sbo_dict = {}
    #catch the version of the packages
    for ver in list_sbo_pkg():
        list_ver.append(ver.split("-")[-3])

    #catch the name of the packages
    for name in list_sbo_pkg():
        match = re.search("[^0-9]+", name)
        print(match.group())

    # make a dict of the form package_name = ver
    zipped_list = zip(list_name, list_ver)
    for name,ver in zipped_list:
        sbo_dict.update({name:ver})

    # look in slackbuilds.txt to compare against the installed package
    file = open("{0}/SLACKBUILDS.TXT".format(tree)).readlines()
    for line in file:
        for name in list_name:
            if "SLACKBUILD NAME: {0}".format(name) in line:
                pass
            
>>>>>>> ba5e6b0982970f82d6b6fa443ce1404462fb5bcc


parser = argparse.ArgumentParser(prog="slackmaster", description="A program to help managing the slackbuilds collection")
parser.add_argument("--sync", help="Sync the tree", action="store_true")
parser.add_argument("--removetree", help="Remove the tree", action="store_true")
parser.add_argument("--status", help="See the status of the tree", action="store_true")
parser.add_argument("--installd", help="Compile dependencies of a slackbuild", metavar="slackbuild")
parser.add_argument("--build", "-b", help="Compile a slackbuild script", metavar="slackbuild", nargs="+")
parser.add_argument("--required", "-r", help="See others slackbuilds scripts that are required to build this package")
parser.add_argument("--search", "-s",  help="Search for slackbuild")
parser.add_argument("--list", help="List packages installed from SBo", action="store_true")
parser.add_argument("--update", help="check for potential update", action="store_true")
args = parser.parse_args()

if args.sync:
    c = Tree()
    c.sync_tree()

if args.list:
    name_list = []
    ver_list = []
    number = 1
    for name in list_sbo_pkg():
        print(name)
        match = re.search('^\w*', name)
        if match:
            name_list.append(name)


    for ver in list_sbo_pkg():
        match = re.search('([0-1000.].*)-x86.*', ver)
        if match:
            print(match.group(1))

            
            
            
             

if args.removetree:
    c = Tree()
    c.remove_tree()

if args.build:
    for elements in args.build:
        print(bcolors.HEADER + "Building {0}...".format(elements) + bcolors.ENDC)
        SlackBuild(elements).build()

if args.required:
    print(loop_required(args.required))
        
if args.search:
    number = 0
    for elements in SlackBuild(args.search).search():
        number = number + 1
        print(number, "-", elements)


